package cn.tannn.cat.file.server.init;

import cn.tannn.cat.file.sdk.config.LocalConfig;
import cn.tannn.cat.file.server.entity.FileStorageConfig;
import cn.tannn.cat.file.server.service.FileStorageConfigService;
import cn.tannn.cat.file.server.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;


/**
 * 映射目录访问路径
 *
 * @author tn
 * @version 1
 * @date 2020/6/18 16:04
 */
@Configuration
@Slf4j
public class LocalInit implements ApplicationRunner {

    /**
     * 存储配置
     */
    @Autowired
    private FileStorageConfigService fileStorageConfigService;
    @Autowired
    private LocalInitDynamicResourceHandlerManager localInitDynamicResourceHandlerManager;


    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<FileStorageConfig> localConfig = fileStorageConfigService.findLocalConfig();
        localConfig.forEach(config -> {
            try {
                LocalConfig local = config.getConfig().toJavaObject(LocalConfig.class);
                if (Objects.nonNull(local)) {
                    String uploadDir = local.getUploadDir();
                    if (uploadDir != null && !uploadDir.isEmpty()) {
                        // 验证目录是否存在
                        if (!FileUtils.exist(uploadDir)) {
                            return;
                        }
                        FileUtils.appendResourceMapping(local
                                , localInitDynamicResourceHandlerManager);
                        log.info("本地磁盘上传配置目录地址: {}, 映射地址：{}", uploadDir, local.getContextPath());
                    }
                }
            } catch (Exception e) {
                log.error("本地磁盘上传配置异常，请检查", e);
            }
        });
    }
}
